<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;



/**
 * 服务提醒通知
 */
class ServiceNotice extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'service_notice';



    /**
     * 服务提醒通知列表
     * @param node 是否批量推送  0全部  1 批量推送  ， 2条件限制
     * @param start_time 推送开始时间
     * @param end_time 推送结束时间
     * @param limit 条数
     */
    public function lists($node, $start_time, $end_time, $limit = 10)
    {
        $res = $this->from($this->getTable() . ' as s')->select('s.id', 's.node', 's.content', 's.wechat_id', 's.account_id', 's.type_name', 's.time', 's.remark', 's.link', 's.is_send', 'm.username','s.create_time')
            ->join('manage as m', 'm.id', '=', 's.manage_id')
            ->where(function ($query) use ($node, $start_time, $end_time) {
                if (!empty($node)) {
                    $query->where('node', $node);
                }
                if (!empty($start_time) && !empty($end_time)) {
                    $query->whereBetween('s.create_time', [$start_time, $end_time]);
                }
            })->orderByDesc('s.id')
            ->where('s.is_del', 1)
            ->paginate($limit)
            ->toArray();


        return $res;
    }
    /**
     * 服务提醒通知详情
     * @param id 数据id
     */
    public function  detail($id)
    {
        $res = $this->select('id', 'node', 'content', 'wechat_id', 'account_id', 'type_name', 'time', 'remark', 'link', 'is_send')
            ->where('id', $id)
            ->where('is_del', 1)
            ->first();

        $res['wechat_info'] = null;
        $res['account_info'] = null;
        if ($res['node'] == 2 && $res['wechat_id']) {
            $wechat_id_arr = explode(',', $res['wechat_id']);
            $userWechatInfoModel = new UserWechatInfo();
            $res['wechat_info'] = $userWechatInfoModel->getWechatByWechatIds($wechat_id_arr);
        }
        if ($res['node'] == 3 && $res['account_id']) {
            $account_id_arr = explode(',', $res['account_id']);
            $userLibraryInfoModel = new UserLibraryInfo();
            $res['account_info'] = $userLibraryInfoModel->getAccountByAccountIds($account_id_arr);
        }

        $time = explode('~', $res['time']);
        $res['start_time'] = $time[0];
        $res['end_time'] = !empty($time[1]) ? $time[1] : '';
        return $res;
    }
}
